package productconsume;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author ufo
 * @Description TODO
 * @Date 2021/1/19 17:42
 * @Version 1.0
 */
public class PCLock {
    public static void main(String[] args) {
        TaskLock task = new TaskLock();
        System.out.println("=====开始=======");
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    task.increase();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "a").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    task.increase();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "b").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 100; i++) {
                    task.increase();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "c").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 300; i++) {
                    task.derease();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "d").start();

    }


}

class TaskLock {
    int num = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increase() throws InterruptedException {
        lock.lock();

        try {
            while (num >= 300) {
                condition.await();
            }
            this.num++;
            System.out.println(Thread.currentThread().getName() + ":" + this.num+"+++");
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public void derease() throws InterruptedException {
        lock.lock();
        try {
            while (num == 0) {
                condition.await();
            }
            this.num--;
            System.out.println(Thread.currentThread().getName() + ":" + this.num+"---");
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
